'''
Created on May 15, 2009

@author: mkiyer
'''

def get_hpeak_bed_line(chrom, chrom_start, chrom_end, strand):
    return '\t'.join([chrom, chrom_start, chrom_end, strand])

def get_bed_line(chrom, chrom_start, chrom_end, strand):
    return '\t'.join([chrom, chrom_start, chrom_end, '.', '.', strand])

class BEDParser(object):
    '''
    Description of the BED file format: http://genome.ucsc.edu/FAQ/FAQformat
    '''
    def __init__(selfparams):
        '''
        Constructor
        '''

    @staticmethod
    def parseBEDFile(fhd):
        '''
        generator func that returns list of bed annotations
        '''
        for thisline in fhd:
            if not thisline:
                continue
            if thisline.startswith("#") or thisline.startswith("track") or thisline.startswith("browser"):
                # TODO: comment line
                continue            
            thisline = thisline.rstrip()
            if not thisline:
                # blank line
                continue
            bedline = BEDAnnotation()
            bedline.parseLine(thisline)
            yield bedline

    @staticmethod
    def filterFile(infhd, outfhd, filterfunc=None):
        '''
        reads a BED file and applies a filter function to every line of annotation
        
        infhd: file descriptor for input file
        outfhd: file descriptor for output file
        
        filterfunc: a function that takes a BEDAnnotation object as input
        and a applies some modifications to the object
        '''
        for thisline in infhd:
            if not thisline:
                continue
            if thisline.startswith("#") or thisline.startswith("track") or thisline.startswith("browser"):
                print >>outfhd, thisline
                continue            
            thisline = thisline.rstrip()
            if not thisline:
                # blank line: don't echo to outfhd
                continue
            bedline = BEDAnnotation()
            bedline.parseLine(thisline)
            # apply filter to bed annotation
            if filterfunc:
                filterfunc(bedline)
            print >>outfhd, bedline

    
class BEDAnnotation(object):
    '''
    From http://genome.ucsc.edu/FAQ/FAQformat#format1:
    
    BED format provides a flexible way to define the data lines that are displayed in an annotation track. 
    
    BED lines have three required fields and nine additional optional fields. The number of fields per line 
    must be consistent throughout any single set of data in an annotation track. 
    
    The order of the optional fields is binding: lower-numbered fields must always be populated if 
    higher-numbered fields are used.

    The first three required BED fields are:
    1. chrom - The name of the chromosome (e.g. chr3, chrY, chr2_random) or scaffold (e.g. scaffold10671).    
    2. chromStart - The starting position of the feature in the chromosome or scaffold. The first base in a chromosome is numbered 0.
    3. chromEnd - The ending position of the feature in the chromosome or scaffold. The chromEnd base is not included in the display of the feature. For example, the first 100 bases of a chromosome are defined as chromStart=0, chromEnd=100, and span the bases numbered 0-99. 

    The 9 additional optional BED fields are:
    4. name - Defines the name of the BED line. This label is displayed to the left of the BED line in the Genome Browser window when the track is open to full display mode or directly to the left of the item in pack mode.
    5. score - A score between 0 and 1000. If the track line useScore attribute is set to 1 for this annotation data set, the score value will determine the level of gray in which this feature is displayed (higher numbers = darker gray).
    6. strand - Defines the strand - either '+' or '-'.
    7. thickStart - The starting position at which the feature is drawn thickly (for example, the start codon in gene displays).
    8. thickEnd - The ending position at which the feature is drawn thickly (for example, the stop codon in gene displays).
    9. itemRgb - An RGB value of the form R,G,B (e.g. 255,0,0). If the track line itemRgb attribute is set to "On", this RBG value will determine the display color of the data contained in this BED line. NOTE: It is recommended that a simple color scheme (eight colors or less) be used with this attribute to avoid overwhelming the color resources of the Genome Browser and your Internet browser.
    10. blockCount - The number of blocks (exons) in the BED line.
    11. blockSizes - A comma-separated list of the block sizes. The number of items in this list should correspond to blockCount.
    12. blockStarts - A comma-separated list of block starts. All of the blockStart positions should be calculated relative to chromStart. The number of items in this list should correspond to blockCount. 
    '''
    def __init__(self):
        '''
        Constructor
        '''
        pass
    
    def __str__(self):
        # required fields
        reqfields = [self.chrom, str(self.chromStart), str(self.chromEnd)]
        # optional fields
        optnames = ['name', 'score', 'strand', 'thickStart', 'thickEnd', 'itemRgb', 'blockCount', 'blockSizes', 'blockStarts']
        optfields = ['.'] * len(optnames)
        maxfield = -1
        # fill optional fields
        for i, attr in enumerate(optnames):
            if hasattr(self, attr):
                optfields[i] = str(getattr(self, attr))
                maxfield = i
        # combine required and optional fields
        allfields = []
        allfields.extend(reqfields)
        allfields.extend(optfields[:(maxfield+1)])
        return '\t'.join(allfields)
    
    def parseLine(self, thisline):
        fields = thisline.strip().split('\t')
        # first three fields are required
        # TODO: throw error if one of first three fields not found
        if len(fields) < 3:
            from veggie.parser.elandparser import ParseError
            print thisline
            raise ParseError('error reading line: %s' % thisline)
        self.chrom = fields.pop(0) 
        self.chromStart = int(fields.pop(0))
        self.chromEnd = int(fields.pop(0))
        # remaining 9 optional fields
        if not len(fields): return
        self.name = fields.pop(0)
        if not len(fields): return
        self.score = float(fields.pop(0))
        if not len(fields): return
        self.strand = fields.pop(0)
        if not len(fields): return
        self.thickStart = int(fields.pop(0))
        if not len(fields): return
        self.thickEnd = int(fields.pop(0))
        if not len(fields): return
        self.itemRgb = fields.pop(0)
        if not len(fields): return
        self.blockCount = int(fields.pop(0))
        if not len(fields): return
        self.blockSizes = fields.pop(0)
        if not len(fields): return
        self.blockStarts = fields.pop(0)
        
        